/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * 迭代实现
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function(root) {
    if(!root)return [];
    let res = [];
    let stack = [root];

    while(stack.length>0){
        let top = stack.pop();
        res.push(top.val);
        //通过入栈顺序得到不同遍历
        if(top.right)stack.push(top.right);
        if(top.left)stack.push(top.left);
    }
    return res;
};